package cn.czh.pet.service.impl;

import cn.czh.pet.domain.PetType;
import cn.czh.pet.mapper.PetTypeMapper;
import cn.czh.pet.service.IPetTypeService;
import cn.czh.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.convert.TypeMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Autowired
    private PetTypeMapper petTypeMapper;

    @Override
    public List<PetType> typeTree() {
        //1.查询所有数据
        List<PetType> petTypes = petTypeMapper.loadAll();
        //2.把查询到的数据放入map集合中
        Map<Long, PetType> map = new HashMap<>();
        //3.遍历所有类型
        for (PetType petType : petTypes) {
            //4.将所有类型装到map中
            map.put(petType.getId(),petType);
        }

        //1.前端需要获得集合数据
        List<PetType> typeTree = new ArrayList<>();
        //2.遍历
        for (PetType petType : petTypes) {
            //3.如果id为null就是顶级类型
            if (petType.getPid()==null){
                typeTree.add(petType);
            }else { //4.不是顶级类型
                //5.获取当前类型的上级类型id
               Long pid = petType.getPid();
               //6.上级部门对象
                PetType parentPetType = map.get(pid);
                //7.将自己装入上级类型的中
                parentPetType.getChildren().add(petType);
            }
        }
        return typeTree;
    }
}
